import { useEffect } from 'react'
import { Drawer, Row, Col, Loading, Space, Table, Button, DialogPlugin, Input, message, Empty } from 'tdesign-react'
import dayjs from 'dayjs'
import styles from './index.module.less'

import type { PrimaryTableCol } from 'tdesign-react'

const TongtoolDetailDrawer = (props: any) => {

  const {
    visible,
    orderInfo = {},
    rowIndex,
    setTableData = () => { },
    onClose,
    setRefundTableData = () => { },
  } = props

  useEffect(() => {
    window.electron.ipcRenderer.on('m2r-refund', (_, item, refundAmount, index, { type, note }) => {
      if (type === 'error') {
        message[type](note)
        return
      }
      setRefundTableData((prevTableData: any[]) => {
        let _prevTableData = structuredClone(prevTableData)
        let currentRecrod = {
          '订单号': item.orderStatus?.orderStatusText?.split(' ')?.[0] || '',
          '下单日期': item.orderStatus?.orderFlowList?.[0]?.time ? dayjs(item.orderStatus?.orderFlowList?.[0]?.time).format('YYYY-MM-DD') : '',
          '通途sku': item.goodsInfo?.[0]?.skuList?.[item.goodsInfo?.[0]?.skuList?.length - 1].split('-')[0],
          '退款原因': '',
          '中文产品名': item.goodsInfo[0].name.split('(')?.[0]?.split('（')?.[0]?.trim(),
          '订单金额': item.TOTALPRICE,
          '退款金额': refundAmount,
        }
        return _prevTableData.concat(currentRecrod)
      })
      setTableData((prevTableData: any[]) => {
        let _tableData = structuredClone(prevTableData)
        _tableData[rowIndex].tongtoolOrderList[index] = item
        return _tableData
      })
      message[type](note)
    })
    window.electron.ipcRenderer.on('m2r-remark', (_, item, index, { type, note }) => {
      if (type === 'error') {
        message[type](note)
        return
      }
      setTableData((prevTableData: any[]) => {
        let _tableData = structuredClone(prevTableData)
        _tableData[rowIndex].tongtoolOrderList[index] = item
        return _tableData
      })
      message[type](note)
    })
    return () => {
      window.electron.ipcRenderer.removeAllListeners('m2r-refund')
      window.electron.ipcRenderer.removeAllListeners('m2r-remark')
    }
  }, [orderInfo])

  /** 订单备注弹窗 */
  const showRemarkDialog = (item: any, index: number) => {
    let remark = ''
    const remarkDialog = DialogPlugin({
      header: '备注',
      body: <div className={styles.remarkDialogContent}>
        <Input
          onChange={(val) => { remark = val }}
          placeholder='请输入订单备注'
        />
      </div>,
      theme: 'default',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        if (!remark) {
          message.error('请输入备注内容')
          return
        }
        window.electron.ipcRenderer.send('r2m-remark', remark, item, index)
        remarkDialog.hide()
      },
      onClose: () => {
        remarkDialog.hide()
      },
      onCloseBtnClick: () => {
        remarkDialog.hide()
      },
    })
  }

  /** 退款弹窗 */
  const showRefundDialog = (item: any, index: number) => {
    let refundAmount = '0'
    const refundDialog = DialogPlugin({
      header: '退款',
      body: <div className={styles.refundDialogContent}>
        <Input
          type='number'
          onChange={(val) => { refundAmount = val }}
          placeholder='请输入退款金额'
        />
      </div>,
      theme: 'default',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        if (isNaN(Number(refundAmount))) {
          message.error('请输入正确的退款金额')
          return
        }
        window.electron.ipcRenderer.send('r2m-refund', refundAmount, item, index)
        refundDialog.hide()
      },
      onClose: () => {
        refundDialog.hide()
      },
      onCloseBtnClick: () => {
        refundDialog.hide()
      },
    })
  }

  /** 补发货弹窗 */
  const showReissueDialog = (item: any, index: number) => {
    const reissueDialog = DialogPlugin({
      header: '补发货',
      body: <div className={styles.reissueDialogContent}></div>,
      theme: 'default',
      style: {
        width: '400px',
      },
      onConfirm: () => {
        window.electron.ipcRenderer.send('r2m-reissue', item, index)
        reissueDialog.hide()
      },
      onClose: () => {
        reissueDialog.hide()
      },
      onCloseBtnClick: () => {
        reissueDialog.hide()
      }
    })
  }

  const historyPayColumns: Array<PrimaryTableCol> = [
    {
      colKey: 'leftText',
      title: '付款日期',
      align: 'center',
      width: 160,
    },
    {
      colKey: 'rightText',
      title: '付款方式+金额',
      align: 'center',
      width: 160,
    }
  ]

  const saleServiceColumns: Array<PrimaryTableCol> = [
    {
      colKey: 'CREATEDDATE',
      title: '处理时间',
      align: 'center',
      width: 160,
    },
    {
      colKey: 'AFTERSALESERVICECODE',
      title: '售后单号',
      align: 'center',
      width: 160,
    },
    {
      colKey: 'AFTERSALESERVICETYPE',
      title: '售后类型',
      align: 'center',
      width: 160,
    },
    {
      colKey: 'REFUNDAMOUNT',
      title: '退款金额',
      align: 'center',
      width: 160,
      cell: ({ row }: { row: any }) => (row.REFUNDAMOUNT || '--') + ' ' + (row.REFUNDCURRENCY || '--')
    },
    {
      colKey: 'CREATEDBY_display',
      title: '操作人',
      align: 'center',
      width: 160,
    },
  ]

  return <Drawer
    className={styles.tongtoolDetailDrawer}
    visible={visible}
    size={'80%'}
    header={null}
    closeBtn={null}
    closeOnOverlayClick={true}
    onOverlayClick={onClose}
    onClose={onClose}
    onConfirm={onClose}
    // showOverlay={false}
  >
    <Loading
      text="正在获取信息..."
      loading={!orderInfo.tongtoolOrderList}
      size="large"
      style={{width: '100%', height: '100%'}}
    >
      <Row style={{paddingBottom: 16, paddingTop: 16}}>
        <Col span={1} className={styles.title}>
          邮箱地址：
        </Col>
        <Col span={11} className={styles.value}>
          {orderInfo.fromMail}
        </Col>
      </Row>
      {orderInfo.tongtoolOrderList && orderInfo.tongtoolOrderList.map((item: any, index: number) => {
        return <Space key={item.ORDERID} direction="vertical">
          <Row>
            <Col span={1} className={styles.title}>包裹状态：</Col>
            {item.orderStatus?.orderFlowList && item.orderStatus.orderFlowList.map((flow: any, index: number) => {
              return <Col className={styles.flowItem} key={index}>
                <div className={`${styles.flowStatus} ${flow.time.trim() ? styles.flowFinished : ''}`}>{flow.status}</div>
                <div className={styles.flowTime}>{flow.time}</div>
              </Col>
            })}
          </Row>
          {item.orderStatus?.orderRemarks && <Row>
            <Col span={1} className={styles.title}>订单备注：</Col>
            {item.orderStatus.orderRemarks.map((remark: any, index: number) => {
              return <Col className={styles.remark} key={index}>
                <div>{remark}</div>
              </Col>
            })}
          </Row>}
          <Row>
            <Col span={12} className={styles.title} style={{paddingBottom: 8}}>商品信息：</Col>
            <Space direction='vertical'>
            {item.goodsInfo && item.goodsInfo.map((goods: any, index: number) => {
              return <Col span={12} key={index} className={styles.goodsInfo}>
                <div>名称：{goods.name}</div>
                <div>SKU: {goods.skuList.join(' ')}</div>
                <div>数量: {goods.count}</div>
              </Col>
            })}
              </Space>
          </Row>
          <Row>
            <Col span={1} className={styles.title}>订单状态：</Col>
            <Col span={3} className={styles.value}>{item.orderStatus.orderStatusText || '没有拿到订单状态'}</Col>
            <Col span={1}> </Col>
            <Col span={1} className={styles.title}>跟踪单号：</Col>
            <Col span={3} className={styles.value}>{item.trackingNo || '没有拿到跟踪单号，可能是没有生成单号'}</Col>
          </Row>
          <Row>
            <Col span={1} className={styles.title}>物流信息：</Col>
            <Col span={8} className={styles.value}>{item.trackingInfo || '没有拿到物流信息'}</Col>
          </Row>
          <Row>
            <Col span={1} className={styles.title}>款项收支：</Col>
            <Col span={11} className={styles.value}>{item.payInfo.totalInfo || '没有拿到总金额信息'}</Col>
          </Row>
          <Row gutter={[0, 16]}>
            <Col span={1} className={styles.title}>历史款项：</Col>
            <Col span={11} className={styles.empty}></Col>
            <Col span={12}>
              <Table
                columns={historyPayColumns}
                data={item.payInfo.historyInfo}
                bordered
                rowKey='item.rightText'
              />
            </Col>
          </Row>
          <Row gutter={[0, 16]}>
            <Col span={1} className={styles.title}>售后记录：</Col>
            <Col span={11} className={styles.empty}></Col>
            <Row>
              <Table
                columns={saleServiceColumns}
                data={item.saleService}
                bordered
                rowKey={'AFTERSALESERVICECODE'}
              ></Table>
            </Row>
          </Row>
          <Row>
            <Space>
              <Button onClick={() => showRemarkDialog(item, index)}>备注</Button>
              <Button onClick={() => showRefundDialog(item, index)}>退款</Button>
              <Button onClick={() => showReissueDialog(item, index)}>补发货</Button>
            </Space>
          </Row>
          <Row>
            <Col span={12}>
              <div>订单备注：{item.remark}</div>
            </Col>
            <Col span={12}>
              <div>本次退款记录：</div>
                {item.refundList && item.refundList.map((refund: string, index: number) => {
                  return <div key={index}>{refund}</div>
                })}
            </Col>
          </Row>
          <p></p>
        </Space>
      })}
      {(orderInfo.tongtoolOrderList && orderInfo.tongtoolOrderList.length === 0) && <Empty title='没有订单' />}
    </Loading>
  </Drawer>
}

export default TongtoolDetailDrawer
